package org.myhibernate.core.method;

import java.sql.Connection;
import java.util.Map;

import org.myhibernate.cache.CacheContainer;
import org.myhibernate.cache.CacheContainers;
import org.myhibernate.cache.RemoveSqlCaches;
import org.myhibernate.core.method.CacheQuery;
import org.myhibernate.core.method.GenericMethod;
import org.myhibernate.db.DataHelper;


public class DeleteMethod<T> extends GenericMethod<T>
{
	private CacheQuery cacheQuery=null;
	public void init(Class cls, Connection connection) 
	{
		super.init(cls, connection);
		cacheQuery=new CacheQuery(connection, cls); 
	} 
	@Override
	public void init(Class cl, DataHelper helper) {
		super.init(cl, helper);
		cacheQuery=new CacheQuery(cl, helper);
	}
	@Override
	public void init(Class cl, Connection connection, DataHelper helper) {
		super.init(cl, connection, helper);
		cacheQuery=new CacheQuery(cl, connection, helper);
	}
	@Override
	public Object execute(Object obj, Map map) throws Exception 
	{
		boolean flag=false;
		
		//delete from database
			getBuffer().append("delete from "+getMapping().getTable()+" where "+getMapping().getId_Column()+"=");
			getBuffer().append(getHandle().handle(obj));
			String sql=getSql();
			try {
				cacheQuery.executeSql(sql);
				//delete sql cache
				new RemoveSqlCaches(getCl());
				//delete from cache
				CacheContainer cacheContainer=CacheContainers.getCache(getCl());
				cacheContainer.remove(obj);
				flag=true;
			} catch (Exception e) 
			{
				e.printStackTrace();
				throw new RuntimeException(e.toString());
			}
		
		return flag;
	}
	@Override
	public void close() {
		cacheQuery.close();
	}
}
